package inits

import (
	"fmt"
	"gateway/global/model"
	"log"
	"time"

	"github.com/redis/go-redis/v9"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func Init(path string) {
	ReadConf(path)
	MysqlConn()
	RedisConn()
}

func RedisConn() {
	model.RDB = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%s", model.Conf.Redis.Host, model.Conf.Redis.Port),
		Password: model.Conf.Redis.Password,
		DB:       0,
	})
	if err := model.RDB.Ping(model.Ctx).Err(); err != nil {
		panic(err)
	}
	fmt.Println("redis conn success")
}

func MysqlConn() {
	DB, err := gorm.Open(mysql.Open(fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", model.Conf.Mysql.User, model.Conf.Mysql.Password, model.Conf.Mysql.Host, model.Conf.Mysql.Port, model.Conf.Mysql.Database)))
	if err != nil {
		log.Println(err.Error())
		return
	}
	db, _ := DB.DB()
	db.SetMaxIdleConns(10)
	db.SetMaxOpenConns(20)
	db.SetConnMaxLifetime(time.Minute * 5)
	model.DB = DB
	fmt.Println("mysql init success")
	model.DB.AutoMigrate(&model.Car{}, &model.Drive{}, &model.Order{}, &model.User{}, &model.WeChats{})
}

func ReadConf(path string) {
	viper.SetConfigFile(fmt.Sprintf("../../config/%s.yaml", path))
	viper.ReadInConfig()
	viper.Unmarshal(&model.Conf)
	fmt.Println(model.Conf)
}
